package com.element.sentinel.exception;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.common.core.exception.code.LimitErrorCode;
import com.common.core.results.VoidResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * web限流异常统一拦截处理
 * 一定要有@Order注解,比默认拦截要优先执行
 *
 * @auther WuJun.Zhang
 * @date 2022/2/18 下午5:28
 */
@Order(value = 1)
@RestControllerAdvice
public class SentinelWebExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(value = BlockException.class)
    public ResponseEntity<VoidResult> blockExceptionHandler(BlockException e) {
        logger.error("接口服务限流:", e);
        return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).body(VoidResult.failed(LimitErrorCode.A_API_LIMIT_ERROR));
    }
}
